﻿#include <vector>
#include <stack>
#include <algorithm>
#include <iostream>

using namespace std;

/*

地址  https://leetcode.cn/problems/maximal-rectangle/


给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵，
找出只包含 1 的最大矩形，并返回其面积。

 
示例 1：
输入：matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出：6
解释：最大矩形如上图所示。

示例 2：
输入：matrix = []
输出：0

示例 3：
输入：matrix = [["0"]]
输出：0

示例 4：
输入：matrix = [["1"]]
输出：1

示例 5：
输入：matrix = [["0","0"]]
输出：0
 


提示：
rows == matrix.length
cols == matrix[0].length
1 <= row, cols <= 200
matrix[i][j] 为 '0' 或 '1'
*/



class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int len = heights.size();
        vector<int> leftmin(len, -1);  vector<int> rightmin(len, len);
        stack<int> st;
        for (int i = 0; i < len; i++) {
            while (!st.empty() && heights[i] <= heights[st.top()]) { st.pop(); }
            if (!st.empty()) { leftmin[i] = st.top(); }
            st.push(i);
        }

        while (!st.empty()) { st.pop(); }

        for (int i = len - 1; i >= 0; i--) {
            while (!st.empty() && heights[i] <= heights[st.top()]) { st.pop(); }
            if (!st.empty()) { rightmin[i] = st.top(); }
            st.push(i);
        }

        int ans = 0;

        for (int i = 0; i < len; i++) {
            int left = leftmin[i];   int right = rightmin[i];
            ans = max(ans, (right - left - 1) * heights[i]);
        }

        cout << ans << endl;
        return ans;
    }

    int maximalRectangle(vector<vector<char>>& matrix) {
        int n = matrix.size(); int m = matrix[0].size();
        if (n == 0 || m == 0) return 0;

        vector<int> heights(m, 0);
        int ans = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (matrix[i][j] == '1') {
                    heights[j]++;
                }
                else {
                    heights[j] = 0;
                }
            }

            ans = max(ans, largestRectangleArea(heights));
        }

        cout << ans << endl;

        return ans;
    }
};

